"""
    JSON文件指定字段抽取
"""

import json

import xlwt as xlwt


def load_file(path):
    """
    加载json文件
    :param path:
    :return: json_data
    """
    try:
        with open(path, 'r+', encoding='utf-8') as f:
            try:
                json_data = json.load(f)
            except Exception as e:
                print('json数据格式不正确：' + str(e))
            return json_data
    except Exception as e:
        print('文件不存在：' + str(e))


#  将数据写入新文件
def data_write(file_path, datas, titles):
    f = xlwt.Workbook()
    sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True)  # 创建sheet
    c = 0
    # 标题栏写入
    for title in titles:
        sheet1.write(0, c, title)
        c += 1
    # 将数据写入第 i 行，第 j 列
    i = 1
    for data in datas:
        for j in range(len(data)):
            sheet1.write(i, j, data[j])
        i = i + 1

    f.save(file_path)  # 保存文件



if __name__ == '__main__':
    obj = load_file(r"C:\CIKE\实验室工作\text2sql\思迈特项目\元数据\data_dict.json")[1]
    i = 0
    temp = []
    for item in obj['header']:
        t = [item['alias'], obj['types'][i], item['fieldType']]
        print(t)
        temp.append(t)
        i += 1
    data_write(r"C:\CIKE\实验室工作\text2sql\思迈特项目\Note\维度说明_source2_138.xlsx", temp, ['column', 'type', 'fieldType'])
    print('total: ' + str(i))
